﻿#define NOAUTOUPGRADE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Resources;
using System.Reflection;
using System.IO;
using System.Net.Http;
using GoldenWOWLauncher.Functions;
using System.Security.Cryptography;
namespace GoldenWOWLauncher
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        protected string CurrentVersion { get { return "202402181132"; } }

        public string RealmList_DEV { get; private set; }

        public ImageBrush Hover;
        
        public ImageBrush noHover;

        public ImageBrush ShowAll;

        public ImageBrush HideAll;

        /// <summary>
        /// 网络连接
        /// </summary>
        LocalServices.Web连接 web;

        /// <summary>
        /// 客户端检查列表
        /// </summary>
        private DataTable ClientCheckList;

        /// <summary>
        /// 电影列表
        /// </summary>
        private List<string> Movies;

        /// <summary>
        /// 电影所在文件夹
        /// </summary>
        private string MoviePath;

        /// <summary>
        /// 电影名称
        /// </summary>
        private string MovieName;

        /// <summary>
        /// 窗体配置文件名
        /// </summary>
        string WindowsConfigPathFileName;

        /// <summary>
        /// Api访问地址配置文件名
        /// </summary>
        string UrlConfigPathFileName;

        public MainWindow()
        {
            RealmList_DEV = "";
            IsLoading = true;
            WindowsConfigPathFileName = String.Empty;
            UrlConfigPathFileName = String.Empty;
            if (System.Environment.ProcessPath != null)
            {
                #region 日志记录
                Logger log = new Logger(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe",  @"\Logs" ), "GoldenWOWLauncher.log", null, true, true);
                Logger.Instance.Log("Start");
                #endregion

                #region 组装当前文件夹
                string[] SplitedPath = System.Environment.ProcessPath.Split(@"\");

                string[] fileName = SplitedPath[SplitedPath.Length - 1].Split('.');
                string AssembledNewPath = string.Empty;
                for (int i = 0; i < SplitedPath.Length - 1; i++)
                {
                    AssembledNewPath += SplitedPath[i] + @"\";
                }
                #endregion

                #region 自动更新自身的逻辑
                try
                {

                    /// 上级自身路径
                    string OlderSelfPath = string.Empty;
                    //string relatedOlderSelfPath = string.Empty;


                    #region 检查自身是更新程序还是正式程序




                    #region 组装正式程序路径和文件名
                    string LauncherPath = AssembledNewPath;
                    LauncherPath += "GoldenWowLauncher.exe";
                    #endregion

                    if (
                        fileName.Length == 3
                        && fileName[2].ToLower() == "exe".ToLower()
                        && fileName[1].ToLower() == "new"
                        && fileName[0].ToLower() == "goldenwowlauncher"
                        )
                    {

                        #region 自身是更新程序

                        #region 删除正式程序
                        try
                        {
                            if (System.IO.File.Exists(LauncherPath))
                            {
                                System.IO.File.Delete(LauncherPath);
                            }
                        }
                        catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }

                        #endregion

                        #region 复制自身为正式程序
                        try
                        {
                            System.IO.File.Copy(System.Environment.ProcessPath, LauncherPath);
                        }
                        catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                        { }
                        #endregion

                        #region 执行正式程序
                        System.Diagnostics.Process.Start(LauncherPath);
                        Environment.Exit(0);
                        #endregion

                        #endregion
                    }
                    else
                    {
                        #region 自身是正式程序

                        #region 组装更新程序
                        string AssembledOldPath = string.Empty;
                        for (int i = 0; i < SplitedPath.Length - 1; i++)
                        {
                            AssembledOldPath += SplitedPath[i] + @"\";
                        }
                        AssembledOldPath += "goldenwowlauncher.new.exe";
                        #endregion

                        #region 删除更新程序
                        try
                        {
                            if (System.IO.File.Exists(AssembledOldPath))
                            {
                                System.IO.File.Delete(AssembledOldPath);
                            }
                        }
                        catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                        { }

                        #endregion

                        #endregion
                    }

                    #endregion
                }
                catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                {

                }
                #endregion

                #region 配置文件的读取和初始化
                Func<string, string, DataSet> MakeConfiguration = (ConfigName, TableName) => {
                    DataSet? thisConfig = null;
                    thisConfig = new DataSet();

                    try
                    {
                        thisConfig.ReadXml(ConfigName);
                    }
                    catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                    { }

                    if (thisConfig == null)
                        thisConfig = new DataSet();

                    try
                    {
                        if (thisConfig.Tables.Count == 0 || !thisConfig.Tables.Contains(TableName))
                        {
                            thisConfig.Tables.Add(TableName);
                        }
                        if (thisConfig != null && thisConfig.Tables != null && thisConfig.Tables.Count > 0 && thisConfig.Tables[TableName] != null)
                        {
                            if (!thisConfig.Tables[TableName].Columns.Contains("item"))
                            {
                                thisConfig.Tables[TableName].Columns.Add("item", typeof(string));
                            }
                            if (!thisConfig.Tables[TableName].Columns.Contains("value"))
                            {
                                thisConfig.Tables[TableName].Columns.Add("value", typeof(string));
                            }
                        }
                    }
                    catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                    { }
                    if (thisConfig != null)
                        return thisConfig;
                    return new DataSet();
                };

                /// 窗体信息配置
                try
                {
                    string _ConfigPathFileName = AssembledNewPath + "LauncherConfig.xml";
                    WindowsConfigPathFileName = _ConfigPathFileName;
                    WindowsConfig = MakeConfiguration(_ConfigPathFileName, "WindowConfiguration");
                }
                catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }

                /// 基础配置
                try
                {
                    string _ConfigPathFileName = AssembledNewPath + "BaseConfig.xml";
                    UrlConfigPathFileName = _ConfigPathFileName;
                    UrlConfig = MakeConfiguration(_ConfigPathFileName, "UrlConfiguration");
                }
                catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                #endregion

            }
            
            InitializeComponent();

            

            #region 关于片头动画的处理

            MoviePath = System.Environment.CurrentDirectory + @"\Data\zhCN\Interface\Cinematics";

            Movies = new List<string>();

            MovieName = string.Empty;

            try
            {
                System.IO.DirectoryInfo dirs = new System.IO.DirectoryInfo(MoviePath);
                foreach (System.IO.FileInfo file in dirs.GetFiles())
                {
                    if (file.Name.Substring(0, 5) == "movie" && file.Name.Substring(file.Name.Length - 4,4) == ".mp4")
                    {
                        Movies.Add(file.FullName);
                    }
                }

                SetRandomMovie();
   
            }
            catch (Exception ex) 
            { 
            }
            #endregion

            web = new LocalServices.Web连接();
            {
                bool ShouldWrite = false;
                try
                {
                    string ApiUrl = LocalServices.ReadItemFromConfig((UrlConfig.Tables["UrlConfiguration"] ?? new DataTable()), "ApiUrl");
                    if (string.IsNullOrEmpty(ApiUrl))
                    {
                        ApiUrl = "http://goldens.world";
                        DataTable dt = UrlConfig.Tables["UrlConfiguration"] ?? new DataTable();
                        dt = dt.Copy();
                        dt.TableName = "UrlConfiguration";
                        LocalServices.SetItemFromConfig(ref dt, "ApiUrl", ApiUrl);
                        UrlConfig.Tables.Remove("UrlConfiguration");
                        UrlConfig.Tables.Add(dt);
                        ShouldWrite = true;
                    }
                    web.Url = ApiUrl;
                } catch { }
                
                try
                {
                    string DefaultRealmListUrl = LocalServices.ReadItemFromConfig((UrlConfig.Tables["UrlConfiguration"] ?? new DataTable()), "DefaultRealmListUrl");
                    if (string.IsNullOrEmpty(DefaultRealmListUrl))
                    {
                        DefaultRealmListUrl = "goldens.world";
                        DataTable dt = UrlConfig.Tables["UrlConfiguration"] ?? new DataTable();
                        dt = dt.Copy();
                        dt.TableName = "UrlConfiguration";
                        LocalServices.SetItemFromConfig(ref dt, "DefaultRealmListUrl", DefaultRealmListUrl);
                        UrlConfig.Tables.Remove("UrlConfiguration");
                        UrlConfig.Tables.Add(dt);
                        ShouldWrite = true;
                    }
                    RealmList = DefaultRealmListUrl;
                } catch { }

                try
                {
                    if (ShouldWrite)
                    {
                        UrlConfig.WriteXml(UrlConfigPathFileName);
                    }
                } catch { }
            }

            ClientCheckList = new DataTable();
            ClientCheckList.Columns.Add("filename", typeof(string));
            ClientCheckList.Columns.Add("hash", typeof(string));
            ClientCheckList.Columns.Add("localpath", typeof(string));
            ClientCheckList.Columns.Add("size", typeof(long));
            ClientCheckList.Columns.Add("time", typeof(string));
            ClientCheckList.Columns.Add("url", typeof(string));

            Hover = new ImageBrush
            {
                ImageSource = new BitmapImage(new Uri("pack://application:,,,/GoldenWOWLauncher;component/Properties/Resources/play_hover.png", UriKind.RelativeOrAbsolute))
            };

            noHover = new ImageBrush
            {
                //  ImageSource = new BitmapImage(new Uri("pack://application:,,,/GoldenWOWLauncher;component/Properties/../play_hover.png", UriKind.Relative))
                ImageSource = new BitmapImage(new Uri("pack://application:,,,/GoldenWOWLauncher;component/Properties/Resources/play_no_hover.png", UriKind.RelativeOrAbsolute))
            };

            ShowAll = new ImageBrush
            {
                ImageSource = new BitmapImage(new Uri("pack://application:,,,/GoldenWOWLauncher;component/Properties/Resources/up.png", UriKind.RelativeOrAbsolute)),
                Stretch = Stretch.Uniform
            };

            HideAll = new ImageBrush
            {
                ImageSource = new BitmapImage(new Uri("pack://application:,,,/GoldenWOWLauncher;component/Properties/Resources/down.png", UriKind.RelativeOrAbsolute)),
                Stretch = Stretch.Uniform
            };

            if (System.IO.File.Exists(Environment.CurrentDirectory + @"\Downloaded\Home.html"))
            {
                web_Home.Source = (new Uri(Environment.CurrentDirectory + @"\Downloaded\Home.html", UriKind.RelativeOrAbsolute));
                HomeURL = web_Home.Source.ToString();
            }
            if (System.IO.File.Exists(Environment.CurrentDirectory + @"\Downloaded\Register.html"))
            {
                web_Register.Source = (new Uri(Environment.CurrentDirectory + @"\Downloaded\Register.html", UriKind.RelativeOrAbsolute));
                RegisterURL = web_Register.Source.ToString();
            }
            if (System.IO.File.Exists(Environment.CurrentDirectory + @"\Downloaded\News.html"))
                NewsURL = (new Uri(Environment.CurrentDirectory + @"\Downloaded\News.html", UriKind.RelativeOrAbsolute)).ToString();


            #region 按照配置文件调整窗口状态
            try
            {
                string WindowState = LocalServices.ReadItemFromConfig(WindowsConfig.Tables["WindowConfiguration"], "WindowState");
                switch (WindowState)
                {
                    case "Normal":
                        {
                            this.WindowState = System.Windows.WindowState.Normal;
                            this.WindowStartupLocation = WindowStartupLocation.Manual;
                            this.btn_Minmal.Visibility = Visibility.Hidden;
                            this.btn_Maximal.Visibility = Visibility.Hidden;
                            this.btn_Exit.Visibility = Visibility.Hidden;
                            this.WindowStyle = WindowStyle.ThreeDBorderWindow;

                            double Height = (double)LocalServices.ToDecimal(LocalServices.ReadItemFromConfig(WindowsConfig.Tables["WindowConfiguration"], "Height"));
                            double Width = (double)LocalServices.ToDecimal(LocalServices.ReadItemFromConfig(WindowsConfig.Tables["WindowConfiguration"], "Width"));
                            if (Height <= this.MinHeight)
                                Height = this.MinHeight;
                            if (Width <= this.MinWidth)
                                Width = this.MinWidth;

                            try { this.Height = Height; }catch(Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                            try { this.Width = Width; } catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }

                            double Top = (double)LocalServices.ToDecimal(LocalServices.ReadItemFromConfig(WindowsConfig.Tables["WindowConfiguration"], "Top"));
                            double Left = (double)LocalServices.ToDecimal(LocalServices.ReadItemFromConfig(WindowsConfig.Tables["WindowConfiguration"], "Left"));

                            if (Top < 0)
                                Top = 0;
                            if (Left < 0)
                                Left = 0;

                            try { this.Top = Top; } catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                            try { this.Left = Left; } catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }

                          
                            
                        }
                        break;
                    case "Maximized":
                    default:
                        //this.WindowState = System.Windows.WindowState.Maximized;
                        break;
                }
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }
            #endregion
            //web_DownloadPage.NavigationCompleted += web_DownloadPage_NavigationCompleted;
            //web_Home.NavigationCompleted += web_Home_NavigationCompleted;
            //web_Register.NavigationCompleted += web_Register_NavigationCompleted;

            lab_Version.Content += CurrentVersion;
        }
     
        private void SetRandomMovie()
        {
            try
            {
                if (Movies.Count > 0)
                {
                    int rand = 0;
                    if (Movies.Count > 1)
                        rand = RandomNumberGenerator.GetInt32(0, Movies.Count - 1);
                    MovieName = Movies[rand];
                }
                    

                if (!string.IsNullOrEmpty(MovieName))
                {
                    media.Source = new Uri(MovieName);
                }
                else
                    media.Source = null;
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }
        }

        private void web_Home_NavigationCompleted(object? sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
        {
            web_Home.Visibility = Visibility.Visible;
        }

        private void web_Register_NavigationCompleted(object? sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
        {
            web_Register.Visibility = Visibility.Visible;
        }

        private void web_DownloadPage_NavigationCompleted(object? sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
        {
                web_DownloadPage.Visibility = Visibility.Visible;
        }

        private enum Status
        { 
            Playable,
            ShouldDownload,
            ShouldUpdate,
        }

        private Status status = Status.Playable;

        /// <summary>
        /// 百度云下载地址
        /// </summary>
        private string FullDownloadUrl = string.Empty;

        /// <summary>
        /// 百度云分享密码
        /// </summary>
        private string FullDownloadCode = string.Empty;

        /// <summary>
        /// 服务器地址
        /// </summary>
        private string RealmList = "103.91.211.64"; 

        /// <summary>
        /// 窗体配置数据
        /// </summary>
        private DataSet WindowsConfig = new DataSet();

        /// <summary>
        /// API地址配置数据
        /// </summary>
        private DataSet UrlConfig = new DataSet();

        protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
        {
            base.OnRenderSizeChanged(sizeInfo);

            if (System.IO.File.Exists(MovieName))
            {
                media.Height = this.Height;
                media.Width = this.Width;
            }

            #region 保存配置文件
            try
            {
                if(!IsLoading)
                {
                    string windowState = "Maximized";
                    switch (this.WindowState)
                    {
                        case WindowState.Normal:
                            windowState = "Normal";
                            break;
                    }
                    DataTable dt = WindowsConfig.Tables["WindowConfiguration"];
                    LocalServices.SetItemFromConfig(ref dt, "WindowState", windowState);
                    LocalServices.SetItemFromConfig(ref dt, "Height", this.Height.ToString());
                    LocalServices.SetItemFromConfig(ref dt, "Width", this.Width.ToString());
                    LocalServices.SetItemFromConfig(ref dt, "Top", this.Top.ToString());
                    LocalServices.SetItemFromConfig(ref dt, "Left", this.Left.ToString());
                    WindowsConfig.WriteXml(WindowsConfigPathFileName);
                }
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }
            #endregion
        }

        protected override void OnLocationChanged(EventArgs e)
        {
            base.OnLocationChanged(e);
            #region 保存配置文件
            try
            {
                if (!IsLoading)
                {
                    string windowState = "Maximized";
                    switch (this.WindowState)
                    {
                        case WindowState.Normal:
                            windowState = "Normal";
                            break;
                    }
                    DataTable dt = WindowsConfig.Tables["WindowConfiguration"];
                    LocalServices.SetItemFromConfig(ref dt, "WindowState", windowState);
                    LocalServices.SetItemFromConfig(ref dt, "Height", this.Height.ToString());
                    LocalServices.SetItemFromConfig(ref dt, "Width", this.Width.ToString());
                    LocalServices.SetItemFromConfig(ref dt, "Top", this.Top.ToString());
                    LocalServices.SetItemFromConfig(ref dt, "Left", this.Left.ToString());
                    WindowsConfig.WriteXml(WindowsConfigPathFileName);
                }
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }
            #endregion
        }

        private bool IsLoading = false;
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //return; // 7号位置
            try { 
            if (System.IO.File.Exists(MovieName))
            {
                //int oheight = media.NaturalVideoHeight;
                //int owidth = media.NaturalVideoWidth;
                //int theight = LocalServices.ToInt(this.Height);
                //int twidth = LocalServices.ToInt(this.Width);
                //int heightTimes = theight / oheight;
                //int widthTimes = twidth / owidth;
                //if (heightTimes < widthTimes)
                //{
                //    media.Height = this.Height;
                //    media.Width = ((double)owidth) * ((double)heightTimes);
                //}
                //else
                //{
                //    media.Width = this.Width;
                //    media.Height = ((double)oheight) * ((double)widthTimes);
                //}
                media.Height = this.Height;
                media.Width = this.Width;

            }
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }
            try {
                btn_Enter.IsEnabled = true;
                lv_Options.Visibility = Visibility.Hidden;
                //btn_Enter.IsEnabled = false;
                txt_Enter.Text = "检查中";
                btn_Enter.IsHitTestVisible = false;
                status = Status.ShouldDownload;
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }
 

            try {
                lv_Options.Items.Clear();
                lv_Options.Items.Add("暂未有可选插件可供下载");
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }
            //return; // 6号位置

            try { btn_News_Click(sender, e); } catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }

            //return; // 5号位置
            #region 访问接口

            /// 通用错误报告
            LocalServices.AfterRequest<KeyValuePair<string, Exception>> errorAfter = (k) => {
                {
                    Exception ex = k.Value;
                    string ProcessName = k.Key;
                    try
                    {
                        Logger.Instance.Log(ProcessName + ":" + ex.Message + ":" + ex.StackTrace);
                    }
                    catch { }
                }
                //MessageBox.Show("访问服务器时遇到问题:\r\n" + ex.Message + "\r\n处理方法请咨询管理员。");
            };

            /// 获得健康列表后
            LocalServices.AfterRequest<List<string>?> healthyClientFileListAfter = (result) => {

                #region 处理健康列表
                try
                {
                    ClientCheckList.Rows.Clear();

                    if (result != null && result.Count > 0)
                    {

                        foreach (string item in result)
                        {
                            Dictionary<string, string> itemDict = LocalServices.JsonToDictionary(item);
                          
                            if (itemDict.ContainsKey("filename")
                            && itemDict.ContainsKey("hash")
                            && itemDict.ContainsKey("localpath")
                            && itemDict.ContainsKey("size")
                            && itemDict.ContainsKey("time")
                            && itemDict.ContainsKey("url")
                            )
                            {
                                DataRow newRow = ClientCheckList.NewRow();
                                newRow["filename"] = itemDict["filename"];
                                newRow["hash"] = itemDict["hash"];
                                newRow["localpath"] = itemDict["localpath"];
                                newRow["size"] = LocalServices.ToLong(itemDict["size"]);
                                newRow["time"] = itemDict["time"];
                                newRow["url"] = itemDict["url"];
                                ClientCheckList.Rows.Add(newRow);
                            }

                        }

                    }

                }
                catch (Exception ex)
                {
                    errorAfter.Invoke(new KeyValuePair<string, Exception>("处理健康列表", ex));
                }
                #endregion

                try
                {
                    string[] Args = System.Environment.GetCommandLineArgs();
                    if (Args != null && Args.Length > 1)
                    {
                        switch (Args[1].ToLower())
                        {
                            case "-developermode":
                            case "-debugmode":
                                #region 特殊模式，禁用自动更新
                                {
                                    LocalServices.RunInAfterCurrentCodes(this, (sender, args) => {
                                        try
                                        {
                                            if (!System.IO.File.Exists(System.Environment.CurrentDirectory + @"\" + "Game.exe"))
                                            {
                                                if (string.IsNullOrEmpty(FullDownloadUrl))
                                                    throw new Exception("服务器未反馈完整下载所需地址");

                                                //web_MainDownload.Navigate(FullDownloadUrl);
                                                //web_MainDownload.Visibility = Visibility.Visible;
                                                //TryOpenWebBrowser(FullDownloadUrl);

                                                //this.lv_Options.Visibility = Visibility.Hidden;


                                                btn_Enter.IsEnabled = false;
                                                btn_Enter.Foreground = new SolidColorBrush(Colors.Black);
                                                txt_Enter.Text = "需下载";
                                                status = Status.ShouldDownload;

                                                btn_FullDownload_Click(sender, e);
                                            }
                                            else
                                            {

                                                //web_MainDownload.Visibility = Visibility.Hidden;
                                                //this.lv_Options.Visibility = Visibility.Visible;
                                                //int ShouldUpdate = RequiresUpdate();
                                                //if (ShouldUpdate == 1)
                                                //{
                                                //    //btn_News_Click(sender, e);
                                                //    btn_Enter.IsEnabled = true;
                                                //    txt_Enter.Text = "更新";
                                                //    status = Status.ShouldUpdate;
                                                //    btn_Enter.IsHitTestVisible = true;
                                                //}
                                                //else if (ShouldUpdate == -1)
                                                {
                                                    //btn_News_Click(sender, e);
                                                    btn_Enter.IsEnabled = true;
                                                    txt_Enter.Text = "进入";
                                                    status = Status.Playable;
                                                    btn_Enter.IsHitTestVisible = true;
                                                }
                                                //else if (ShouldUpdate == 2)
                                                //{

                                                //    btn_Enter.IsEnabled = false;
                                                //    btn_Enter.Foreground = new SolidColorBrush(Colors.Black);
                                                //    txt_Enter.Text = "需下载";
                                                //    status = Status.ShouldDownload;
                                                //    MessageBox.Show("你所用的客户端和本服务器不完全匹配，强行使用可能会存在的风险包括而不限于贴图错误，模型错误，弹窗报错，客户端崩溃弹出。\r\n请完整下载本服客户端以登入服务器。");
                                                //    btn_FullDownload_Click(sender, e);
                                                //}
                                                //else
                                                //{
                                                //    //btn_News_Click(sender, e);
                                                //    try
                                                //    {
                                                //        #region 更新按钮状态
                                                //        btn_Enter.IsEnabled = true;
                                                //        txt_Enter.Text = "更新中";
                                                //        status = Status.ShouldDownload;
                                                //        btn_Enter.IsHitTestVisible = false;
                                                //        #endregion
                                                //    }
                                                //    catch
                                                //    { }

                                                //    try
                                                //    {
                                                //        #region 更新自己
                                                //        if (UpdateQueue != null && UpdateQueue.Count > 0 && Environment.ProcessPath != null)
                                                //        {
                                                //            // 断言此处只有一行记录，就是更新自己的记录
                                                //            pgb_Download.Visibility = Visibility.Hidden;
                                                //            pgb_Download.Maximum = 1000;
                                                //            pgb_Download.Minimum = 0;
                                                //            pgb_Download.Value = 0;
                                                //            DataRow row = UpdateQueue[0];
                                                //            //long size = Services.ToLong(row["size"]);
                                                //            //string hash = Services.ToString(row["hash"]);
                                                //            string url = LocalServices.ToString(row["url"]);
                                                //            //string filename = LocalServices.ToString(row["filename"]);
                                                //            string filename = @"downloaded\goldenwowlauncher.exe";
                                                //            //string localpath = LocalServices.ToString(row["localpath"]);
                                                //            string localpath = "";
                                                //            if (DOWNLOADER != null)
                                                //            {
                                                //                try
                                                //                {
                                                //                    DOWNLOADER.Dispose();
                                                //                    DOWNLOADER = null;
                                                //                }
                                                //                catch (Exception ex)
                                                //                { }
                                                //            }
                                                //            DOWNLOADER = new System.Net.WebClient();
                                                //            {
                                                //                DOWNLOADER.DownloadProgressChanged += DOWNLOADER_DownloadProgressChanged;
                                                //                DOWNLOADER.DownloadFileCompleted += (sender, e) => {

                                                //                    this.Dispatcher.Invoke(new Action(() => {
                                                //                        pgb_Download.Value = pgb_Download.Maximum;
                                                //                    }));

                                                //                    this.Dispatcher.Invoke(new Action(() => {
                                                //                        try
                                                //                        {
                                                //                            if (Environment.ProcessPath != null)
                                                //                            {
                                                //                                //DataRow DownloadingRow = UpdateQueue[0];
                                                //                                //string url = LocalServices.ToString(DownloadingRow["url"]);
                                                //                                //string filename = LocalServices.ToString(DownloadingRow["filename"]);
                                                //                                //string localpath = Services.ToString(DownloadingRow["localpath"]);

                                                //                                //FullPathEnsure(localpath);

                                                //                                MessageBox.Show("下载完成，即将关闭本程序以更新登录器。");

                                                //                                #region 运行已更新程序
                                                //                                try
                                                //                                {
                                                //                                    System.Diagnostics.Process.Start(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", filename));
                                                //                                }
                                                //                                catch
                                                //                                { }
                                                //                                #endregion

                                                //                                #region 退出本程序
                                                //                                System.Environment.Exit(0);
                                                //                                #endregion

                                                //                            }

                                                //                        }
                                                //                        catch
                                                //                        { }
                                                //                    }));
                                                //                }; ;

                                                //                FullPathEnsure("Downloaded");

                                                //                #region 先下载到临时文件夹

                                                //                #region 先删
                                                //                if (!System.IO.File.Exists(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", filename)))
                                                //                {
                                                //                    try
                                                //                    {
                                                //                        System.IO.File.Delete(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", filename));
                                                //                    }
                                                //                    catch
                                                //                    { }
                                                //                }
                                                //                #endregion

                                                //                #region 后下
                                                //                {

                                                //                    DOWNLOADER.DownloadFileAsync(new Uri(url), Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", filename));
                                                //                    pgb_Download.Visibility = Visibility.Visible;
                                                //                }
                                                //                #endregion

                                                //                #endregion
                                                //            }

                                                //        }
                                                //        #endregion
                                                //    }
                                                //    catch
                                                //    { }

                                                //}


                                            }

                                        }
                                        catch (Exception ex)
                                        {
                                            { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                            MessageBox.Show("自动检查时遇到错误。\r\n你可以继续使用登录器进入游戏，但依然请尽快联系管理员跟进处理。");
                                            //btn_News_Click(sender, e);
                                            btn_Enter.IsEnabled = true;
                                            txt_Enter.Text = "进入";
                                            status = Status.Playable;
                                            btn_Enter.IsHitTestVisible = true;
                                        }
                                    });
                                }
                                #endregion
                                
                                break;
                        }

                        switch (Args[1].ToLower())
                        {
                            case "-developermode":
                                RealmList = RealmList_DEV;
                                return;
                            case "-debugmode":
                                return;
                        }
                    }
                    #region 正常模式，检查自动更新
                    {

                        LocalServices.RunInAfterCurrentCodes(this, (sender, args) => {
                            try
                            {
                                if (!System.IO.File.Exists(System.Environment.CurrentDirectory + @"\" + "Game.exe"))
                                {
                                    if (string.IsNullOrEmpty(FullDownloadUrl))
                                        throw new Exception("服务器未反馈完整下载所需地址");

                                    //web_MainDownload.Navigate(FullDownloadUrl);
                                    //web_MainDownload.Visibility = Visibility.Visible;
                                    //TryOpenWebBrowser(FullDownloadUrl);

                                    //this.lv_Options.Visibility = Visibility.Hidden;


                                    btn_Enter.IsEnabled = false;
                                    btn_Enter.Foreground = new SolidColorBrush(Colors.Black);
                                    txt_Enter.Text = "需下载";
                                    status = Status.ShouldDownload;

                                    btn_FullDownload_Click(null, e);
                                }
                                else
                                {

                                    //web_MainDownload.Visibility = Visibility.Hidden;
                                    //this.lv_Options.Visibility = Visibility.Visible;
                                    int ShouldUpdate = RequiresUpdate();
                                    if (ShouldUpdate == 1)
                                    {
                                        //btn_News_Click(sender, e);
                                        btn_Enter.IsEnabled = true;
                                        txt_Enter.Text = "更新";
                                        status = Status.ShouldUpdate;
                                        btn_Enter.IsHitTestVisible = true;
                                    }
                                    else if (ShouldUpdate == -1)
                                    {
                                        //btn_News_Click(sender, e);
                                        btn_Enter.IsEnabled = true;
                                        txt_Enter.Text = "进入";
                                        status = Status.Playable;
                                        btn_Enter.IsHitTestVisible = true;
                                    }
                                    else if (ShouldUpdate == 2)
                                    {

                                        btn_Enter.IsEnabled = false;
                                        btn_Enter.Foreground = new SolidColorBrush(Colors.Black);
                                        txt_Enter.Text = "需下载";
                                        status = Status.ShouldDownload;
                                        MessageBox.Show("你所用的客户端和本服务器不完全匹配，强行使用可能会存在的风险包括而不限于贴图错误，模型错误，弹窗报错，客户端崩溃弹出。\r\n请完整下载本服客户端以登入服务器。");
                                        btn_FullDownload_Click(null, e);
                                    }
                                    else
                                    {
                                        //btn_News_Click(sender, e);
                                        try
                                        {
                                            #region 更新按钮状态
                                            btn_Enter.IsEnabled = true;
                                            txt_Enter.Text = "更新中";
                                            status = Status.ShouldDownload;
                                            btn_Enter.IsHitTestVisible = false;
                                            #endregion
                                        }
                                        catch
                                        { }

                                        try
                                        {
                                            #region 更新自己
                                            if (UpdateQueue != null && UpdateQueue.Count > 0 && Environment.ProcessPath != null)
                                            {
                                                // 断言此处只有一行记录，就是更新自己的记录
                                                pgb_Download.Visibility = Visibility.Hidden;
                                                pgb_Download.Maximum = 1000;
                                                pgb_Download.Minimum = 0;
                                                pgb_Download.Value = 0;
                                                DataRow row = UpdateQueue[0];
                                                //long size = Services.ToLong(row["size"]);
                                                //string hash = Services.ToString(row["hash"]);
                                                string url = LocalServices.ToString(row["url"]);
                                                //string filename = LocalServices.ToString(row["filename"]);
                                                string filename = @"downloaded\goldenwowlauncher.exe";
                                                //string localpath = LocalServices.ToString(row["localpath"]);
                                                string localpath = "";
                                                if (DOWNLOADER != null)
                                                {
                                                    try
                                                    {
                                                        DOWNLOADER.Dispose();
                                                        DOWNLOADER = null;
                                                    }
                                                    catch (Exception ex)
                                                    { }
                                                }
                                                DOWNLOADER = new System.Net.WebClient();
                                                {
                                                    DOWNLOADER.DownloadProgressChanged += DOWNLOADER_DownloadProgressChanged;
                                                    DOWNLOADER.DownloadFileCompleted += (sender, e) => {

                                                        this.Dispatcher.Invoke(new Action(() => {
                                                            pgb_Download.Value = pgb_Download.Maximum;
                                                        }));

                                                        this.Dispatcher.Invoke(new Action(() => {
                                                            try
                                                            {
                                                                if (Environment.ProcessPath != null)
                                                                {
                                                                    //DataRow DownloadingRow = UpdateQueue[0];
                                                                    //string url = LocalServices.ToString(DownloadingRow["url"]);
                                                                    //string filename = LocalServices.ToString(DownloadingRow["filename"]);
                                                                    //string localpath = Services.ToString(DownloadingRow["localpath"]);

                                                                    //FullPathEnsure(localpath);

                                                                    MessageBox.Show("下载完成，即将关闭本程序以更新登录器。");

                                                                    #region 运行已更新程序
                                                                    try
                                                                    {
                                                                        System.Diagnostics.Process.Start(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", filename));
                                                                    }
                                                                    catch
                                                                    { }
                                                                    #endregion

                                                                    #region 退出本程序
                                                                    System.Environment.Exit(0);
                                                                    #endregion

                                                                }

                                                            }
                                                            catch
                                                            { }
                                                        }));
                                                    }; ;

                                                    FullPathEnsure("Downloaded");

                                                    #region 先下载到临时文件夹

                                                    #region 先删
                                                    if (!System.IO.File.Exists(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", filename)))
                                                    {
                                                        try
                                                        {
                                                            System.IO.File.Delete(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", filename));
                                                        }
                                                        catch
                                                        { }
                                                    }
                                                    #endregion

                                                    #region 后下
                                                    {

                                                        DOWNLOADER.DownloadFileAsync(new Uri(url), Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", filename));
                                                        pgb_Download.Visibility = Visibility.Visible;
                                                    }
                                                    #endregion

                                                    #endregion
                                                }

                                            }
                                            #endregion
                                        }
                                        catch
                                        { }

                                    }


                                }

                            }
                            catch
                            {

                                MessageBox.Show("自动检查时遇到错误。\r\n你可以继续使用登录器进入游戏，但依然请尽快联系管理员跟进处理。");
                                //btn_News_Click(sender, e);
                                btn_Enter.IsEnabled = true;
                                txt_Enter.Text = "进入";
                                status = Status.Playable;
                                btn_Enter.IsHitTestVisible = true;
                            }
                        });

                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    errorAfter.Invoke(new KeyValuePair<string, Exception>("启动模式处理及自动更新", ex));
                }

          
            };

            /// 百度云错误报告
            LocalServices.AfterRequest<KeyValuePair<string,Exception>> baiduClouderrorAfter = (k) => {
                Exception ex = k.Value;
                MessageBox.Show("获取客户端下载方式时遇到问题:\r\n" + ex.Message + "\r\n下载页面可能暂时无法使用。");
                FullDownloadUrl = string.Empty;
                try
                {
                    /// 访问健康列表
                    web.FetchList("healthyClientFileList", "", healthyClientFileListAfter, errorAfter);
                }
                catch (Exception exx)
                {
                    errorAfter.Invoke(new KeyValuePair<string, Exception>(k.Key, exx));
                }
            };

            /// 获得云盘地址后
            LocalServices.AfterRequest<List<string>?> baiduCloudAfter = (result) => {

#region 处理下载地址
                try
                {
                    if (result != null && result.Count > 0)
                    {
                        // 暂时只处理第一个云盘
                        Dictionary<string, string> cloudDisk1 = LocalServices.JsonToDictionary(result[0]);

                        if (cloudDisk1.ContainsKey("url")
                        && cloudDisk1.ContainsKey("time")
                        && cloudDisk1.ContainsKey("code")
                        )
                        {
                            FullDownloadUrl = LocalServices.ConvertUnicodeToUtf8(cloudDisk1["url"]);
                            FullDownloadCode = LocalServices.ConvertUnicodeToUtf8(cloudDisk1["code"]);
                            //web_DownloadPage.NavigateToString(FullDownloadUrl);
                            TryOpenDownloadWebBrowser(FullDownloadUrl);
                        }
                        //FullDownloadUrl += "?pwd=" + FullDownloadCode;
                    }

                }
                catch (Exception ex)
                {
                    errorAfter.Invoke(new KeyValuePair<string, Exception>("处理下载地址", ex));
                }
#endregion


                try
                {
                    /// 访问健康列表
                    web.FetchList("healthyClientFileList", "", healthyClientFileListAfter, errorAfter);
                }
                catch (Exception ex)
                {
                    errorAfter.Invoke(new KeyValuePair<string, Exception>("访问健康列表", ex));
                }


            };

            /// 获得新闻后
            LocalServices.AfterRequest<List<string>?> newsAfter = (result) =>
            {


                try
                {
                    msg_News.DataSource = result;

                }
                catch (Exception ex)
                {
                    errorAfter.Invoke(new KeyValuePair<string, Exception>("获得新闻后", ex));
                }


               
            };

            /// 获得按钮后
#region 处理按钮
            LocalServices.AfterRequest<List<string>?> buttonsAfter = (result) =>
            {
                
                try
                {
                    if (result != null && result.Count > 0)
                    {
                        foreach (string r in result)
                        {
                            Dictionary<string, string> buttonsItem1 = LocalServices.JsonToDictionary(r);

                            {
                                string button_name = string.Empty;
                                if (buttonsItem1.ContainsKey("button_name"))
                                    button_name = LocalServices.ConvertUnicodeToUtf8(buttonsItem1["button_name"]);

                                string button_url = string.Empty;
                                if (buttonsItem1.ContainsKey("button_url"))
                                    button_url = LocalServices.ConvertUnicodeToUtf8(buttonsItem1["button_url"]);

                                string offline_html = string.Empty;
                                if (buttonsItem1.ContainsKey("offline_html"))
                                    offline_html = LocalServices.ConvertUnicodeToUtf8(buttonsItem1["offline_html"]);

                                string remark = string.Empty;
                                if (buttonsItem1.ContainsKey("remark"))
                                    remark = LocalServices.ConvertUnicodeToUtf8(buttonsItem1["remark"]);

                                string time = string.Empty;
                                if (buttonsItem1.ContainsKey("time"))
                                    time = LocalServices.ConvertUnicodeToUtf8(buttonsItem1["time"]);

                                switch (button_name)
                                {
                                    case "新闻":
                                        if (!string.IsNullOrEmpty(offline_html))
                                        {
                                            string targetfilename = "News.html";
                               
                                            string[] splitedhtml = offline_html.Split('/');
                                            string filename = "";

                                            if (splitedhtml != null && splitedhtml.Length > 0)
                                                filename = splitedhtml[splitedhtml.Length - 1];
                                            string url = offline_html;

                                            if (!string.IsNullOrEmpty(filename))
                                            {
                                                LocalServices.RunInAfterCurrentCodes(this, (s, e) =>
                                                {
                                                    
                                                    System.Net.WebClient tempDownloader = new System.Net.WebClient();
                                                    tempDownloader.DownloadFileCompleted += (sender, e) =>
                                                    {

                                                        this.Dispatcher.Invoke(new Action(() =>
                                                        {
                                                            try
                                                            {
                                                                if (Environment.ProcessPath != null)
                                                                {
                                                                    bool IsNewer = false;
#region 检查更新
                                                                    string hashLocal = string.Empty;
                                                                    if (System.IO.File.Exists(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + targetfilename)))
                                                                        hashLocal = LocalServices.GetMD5HashFromFile(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + targetfilename));
                                                                    string hashRemote = LocalServices.GetMD5HashFromFile(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename));
                                                                    if (hashRemote != hashLocal)
                                                                    {
                                                                        IsNewer = true;
                                                                    }
#endregion

#region 如果已经更新，则替换
                                                                    try
                                                                    {
                                                                        if (IsNewer)
                                                                        {
                                                                            try
                                                                            {
                                                                                System.IO.File.Delete(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + targetfilename));
                                                                            }
                                                                            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                                                            { }
                                                                            try
                                                                            {
                                                                                System.IO.File.Copy(
                                                                                Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename)
                                                                                ,
                                                                                Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + targetfilename)
                                                                                );
                                                                            }
                                                                            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                                                            { }


                                                                            NewsURL = (new Uri(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + targetfilename))).ToString();
                                                                        }
                                                                    }
                                                                    catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                                                    { }
#endregion

                                                                }

                                                            }
                                                            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                                            { }

                                                            tempDownloader.Dispose();
                                                        }));

                                                       
                                                    }; ;

                                                    FullPathEnsure("Downloaded");

#region 先下载到临时文件夹

#region 先删
                                                    if (!System.IO.File.Exists(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename)))
                                                    {
                                                        try
                                                        {
                                                            System.IO.File.Delete(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename));
                                                        }
                                                        catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                                        { }
                                                    }
#endregion

#region 后下
                                                    {

                                                        tempDownloader.DownloadFileAsync(new Uri(url), Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename));
                                                        //pgb_Download.Visibility = Visibility.Visible;
                                                    }
#endregion

#endregion
                                                });

                                            }
                                        }
                                        //else if (!string.IsNullOrEmpty(button_url))
                                        //    NewsURL = button_url;
                                        break;
                                    case "社区":
                                        if (!string.IsNullOrEmpty(button_url))
                                            HomeURL = button_url;
//                                        if (!string.IsNullOrEmpty(offline_html))
//                                        {
//                                            string targetfilename = "Home.html";

//                                            string[] splitedhtml = offline_html.Split('/');
//                                            string filename = "";

//                                            if (splitedhtml != null && splitedhtml.Length > 0)
//                                                filename = splitedhtml[splitedhtml.Length - 1];
//                                            string url = offline_html;

//                                            if (!string.IsNullOrEmpty(filename))
//                                            {
//                                                LocalServices.RunInAfterCurrentCodes(this, (s, e) =>
//                                                {

//                                                    System.Net.WebClient tempDownloader = new System.Net.WebClient();
//                                                    tempDownloader.DownloadFileCompleted += (sender, e) =>
//                                                    {

                                                
//                                                        this.Dispatcher.Invoke(new Action(() =>
//                                                        {
//                                                            try
//                                                            {
//                                                                if (Environment.ProcessPath != null)
//                                                                {
//                                                                    bool IsNewer = false;

//#region 检查更新
//                                                                    string hashLocal = string.Empty;
//                                                                    if (System.IO.File.Exists(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + targetfilename)))
//                                                                        hashLocal = LocalServices.GetMD5HashFromFile(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + targetfilename));
//                                                                    string hashRemote = LocalServices.GetMD5HashFromFile(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename));
//                                                                    if (hashRemote != hashLocal)
//                                                                    {
//                                                                        IsNewer = true;
//                                                                    }
//#endregion

//#region 如果已经更新，则替换
//                                                                    try
//                                                                    {
//                                                                        if (IsNewer)
//                                                                        {
//                                                                            try
//                                                                            {
//                                                                                System.IO.File.Delete(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + targetfilename));
//                                                                            }
//                                                                            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
//                                                                            { }
//                                                                            try
//                                                                            {
//                                                                                System.IO.File.Copy(
//                                                                                Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename)
//                                                                                ,
//                                                                                Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + targetfilename)
//                                                                                );
//                                                                            }
//                                                                            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
//                                                                            { }

//                                                                            try
//                                                                            {
//                                                                                System.IO.File.Delete(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename));
//                                                                            }
//                                                                            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
//                                                                            { }

//                                                                        }

//                                                                        HomeURL = (new Uri(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + targetfilename))).ToString();
//                                                                        TryOpenHomeWebBrowser(HomeURL);
//                                                                    }
//                                                                    catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
//                                                                    { }
//#endregion

//                                                                }

                                                              
//                                                            }
//                                                            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
//                                                            { }

//                                                            tempDownloader.Dispose();
//                                                        }));

                                                 
//                                                    }; ;

//                                                    FullPathEnsure("Downloaded");

//#region 先下载到临时文件夹

//#region 先删
//                                                    if (!System.IO.File.Exists(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename)))
//                                                    {
//                                                        try
//                                                        {
//                                                            System.IO.File.Delete(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename));
//                                                        }
//                                                        catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
//                                                        { }
//                                                    }
//#endregion

//#region 后下
//                                                    {

//                                                        tempDownloader.DownloadFileAsync(new Uri(url), Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename));
//                                                        //pgb_Download.Visibility = Visibility.Visible;
//                                                    }
//#endregion

//#endregion

                                               
//                                                });
//                                            }
//                                        }
//                                        else
                                        {
                                            TryOpenHomeWebBrowser(HomeURL);
                                        }
                                        //
                                        break;
                                    case "注册":
                                        if (!string.IsNullOrEmpty(button_url))
                                            RegisterURL = button_url;
                                        if (!string.IsNullOrEmpty(offline_html))
                                        {
                                            string targetfilename = "Register.html";

                                            string[] splitedhtml = offline_html.Split('/');
                                            string filename = "";

                                            if (splitedhtml != null && splitedhtml.Length > 0)
                                                filename = splitedhtml[splitedhtml.Length - 1];
                                            string url = offline_html;

                                            if (!string.IsNullOrEmpty(filename))
                                            {
                                                LocalServices.RunInAfterCurrentCodes(this, (s, e) =>
                                                {

                                                    System.Net.WebClient TempDownloader = new System.Net.WebClient();
                                                    //DOWNLOADER.DownloadProgressChanged += DOWNLOADER_DownloadProgressChanged;
                                                    TempDownloader.DownloadFileCompleted += (sender, e) =>
                                                    {

                                                        this.Dispatcher.Invoke(new Action(() =>
                                                        {
                                                            try
                                                            {
                                                                if (Environment.ProcessPath != null)
                                                                {
                                                                    bool IsNewer = false;
                                                                    #region 检查更新
                                                                    string hashLocal = string.Empty;
                                                                    if (System.IO.File.Exists(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + targetfilename)))
                                                                        hashLocal = LocalServices.GetMD5HashFromFile(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + targetfilename));
                                                                    string hashRemote = LocalServices.GetMD5HashFromFile(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename));
                                                                    if (hashRemote != hashLocal)
                                                                    {
                                                                        IsNewer = true;
                                                                    }
                                                                    #endregion

                                                                    #region 如果已经更新，则替换
                                                                    try
                                                                    {
                                                                        if (IsNewer)
                                                                        {
                                                                            try
                                                                            {
                                                                                System.IO.File.Delete(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + targetfilename));
                                                                            }
                                                                            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                                                            { }
                                                                            try
                                                                            {
                                                                                System.IO.File.Copy(
                                                                                Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename)
                                                                                ,
                                                                                Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + targetfilename)
                                                                                );
                                                                            }
                                                                            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                                                            { }

                                                                            try
                                                                            {
                                                                                System.IO.File.Delete(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename));
                                                                            }
                                                                            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                                                            { }

                                                                        }
                                                                        RegisterURL = (new Uri(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + targetfilename))).ToString();
                                                                        TryOpenRegisterWebBrowser(RegisterURL);
                                                                    }
                                                                    catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                                                    { }
                                                                    #endregion


                                                                }

                                                            }
                                                            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                                            { }

                                                            TempDownloader.Dispose();
                                                        }));

                                                    }; ;

                                                    FullPathEnsure("Downloaded");

                                                    #region 先下载到临时文件夹

                                                    #region 先删
                                                    if (!System.IO.File.Exists(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename)))
                                                    {
                                                        try
                                                        {
                                                            System.IO.File.Delete(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename));
                                                        }
                                                        catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                                        { }
                                                    }
                                                    #endregion

                                                    #region 后下
                                                    {

                                                        TempDownloader.DownloadFileAsync(new Uri(url), Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename));
                                                        //pgb_Download.Visibility = Visibility.Visible;
                                                    }
                                                    #endregion

                                                    #endregion

                                                    //web_Register.NavigateToString("Downloaded" + @"\" + filename);

                                                });

                                            }
                                        }
                                        else
                                        {
                                            TryOpenRegisterWebBrowser(RegisterURL);
                                        }
                                        //TryOpenRegisterWebBrowser(RegisterURL);

                                        break;
                                    case "下载":
                                        // 网盘一般没法做缓存
                                        if (!string.IsNullOrEmpty(button_url))
                                        {
                                            FullDownloadUrl = button_url;
                                           
                                        }
                                        break;
                                    case "插件":
                                        break;
                                    case "realmlist":
                                        if (!string.IsNullOrEmpty(button_url)) 
                                        {
                                            RealmList = button_url;
                                        }
                                        break;
                                    case "developer_realm":
                                        if (!string.IsNullOrEmpty(button_url))
                                        {
                                            RealmList_DEV = button_url;
                                            RealmList = RealmList_DEV;
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }


                    }

                }
                catch (Exception ex)
                {
                    errorAfter.Invoke(new KeyValuePair<string, Exception>("获得按钮后", ex));
                }



            };
#endregion

#region 请求查询
            //return; // 4号位置
            try
            {

                /// 访问按钮
                web.FetchList("buttons", "", buttonsAfter, errorAfter);
            }
            catch (Exception ex)
            {
                errorAfter.Invoke(new KeyValuePair<string, Exception>("访问按钮", ex));
            }
            //return; // 3号位置
            try
            {

                /// 访问新闻
                web.FetchList("news", "", newsAfter, errorAfter);
            }
            catch (Exception ex)
            {
                errorAfter.Invoke(new KeyValuePair<string, Exception>("访问新闻", ex));
            }
            //return; // 2号位置
            try
            {

                /// 访问百度云地址
                web.FetchList("baiduCloud", "", baiduCloudAfter, baiduClouderrorAfter);
            }
            catch (Exception ex)
            {
                errorAfter.Invoke(new KeyValuePair<string, Exception>("访问百度云地址", ex));
            }
            //return; // 1号位置

#endregion

#endregion

            IsLoading = false;
        }

        /// <summary>
        /// 异步工作登记本
        /// </summary>
        Dictionary<string, System.ComponentModel.BackgroundWorker?> LastBGs = new Dictionary<string, BackgroundWorker?>();

        private static int triedDownloadWebTimes = 0;
        private static bool IsDownloadWebReady = false;
        private void TryOpenDownloadWebBrowser(string url)
        {
            if (LastBGs.ContainsKey("Download") && LastBGs["Download"] != null) // 如果已经在工作中，就没必要重复发起工作了
                return;

            LastBGs["Download"] = new BackgroundWorker();

            if (triedDownloadWebTimes <= 5)
            {
                if (web_DownloadPage.CoreWebView2 == null)
                {
                    if (web_DownloadPage.Source != new Uri(url))
                    {
                        web_DownloadPage.Source = new Uri(url);
                        web_DownloadPage.EnsureCoreWebView2Async();
                    }
                }
                else
                {
                    web_DownloadPage.NavigateToString(url);
                    LastBGs.Remove("Download");
                    return;

                }
            }
            if (LastBGs["Download"] != null)
            {
                LastBGs["Download"].DoWork += (s, e) =>
                {
                 
                    try
                    {
                        while (!IsDownloadWebReady)
                        {
                            if (triedDownloadWebTimes > 5)
                                IsDownloadWebReady = true;

                            System.Threading.Thread.Sleep(500);
                            this.Dispatcher.InvokeAsync(new Action(() =>
                            {
                                
                                try
                                {
                                    IsDownloadWebReady = web_DownloadPage.CoreWebView2 != null;
#if DEBUG
                                    //IsDownloadWebReady = false;
#endif
                                }
                                catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                { }
                            }));
                            triedDownloadWebTimes++;
     
                        }
                    }
                    catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                    { }
                };
                LastBGs["Download"].RunWorkerCompleted += (s, e) =>
                {
                    //this.Dispatcher.InvokeAsync(new Action(() => {

                    try
                    {
                        if (triedDownloadWebTimes <= 5 && web_DownloadPage != null && web_DownloadPage.CoreWebView2 != null)
                        {
                            if (!string.IsNullOrEmpty(url) && web_DownloadPage.Source != new Uri(url))
                                web_DownloadPage.CoreWebView2.Navigate(url /*+ "?pwd=" + FullDownloadCode*/);

                        }
                        else
                        {
                            //TryOpenDownloadWebBrowser(url);
                            //System.Diagnostics.Process.Start("explorer.exe", url);
                        }

                    }
                    catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                    { }
                    LastBGs.Remove("Download");
                    //}));
                };
                LastBGs["Download"].RunWorkerAsync();
            }

        }

        private static int triedHomeWebTimes = 0;
        private static bool IsHomeWebReady = false;
        private void TryOpenHomeWebBrowser(string url)
        {
            if (LastBGs.ContainsKey("Home") && LastBGs["Home"] != null) // 如果已经在工作中，就没必要重复发起工作了
                return;

            LastBGs["Home"] = new BackgroundWorker();
            if (triedHomeWebTimes <= 5)
            {

                if (web_DownloadPage.CoreWebView2 == null)
                {
                    if (web_Home.Source != new Uri(url))
                    {
                        web_Home.Source = new Uri(url);
                        web_Home.EnsureCoreWebView2Async();
                    }
                    

                }
                else
                {
                    web_Home.NavigateToString(url);
                    LastBGs.Remove("Home");
                    return;
                }
            }
         
            if (LastBGs["Home"] != null)
            {
                //web_Home.EnsureCoreWebView2Async();
                LastBGs["Home"].DoWork += (s, e) =>
                {
                   
                    try
                    {
                        while (!IsHomeWebReady)
                        {
                            if (triedHomeWebTimes > 5)
                                IsHomeWebReady = true;
                            System.Threading.Thread.Sleep(500);
                            this.Dispatcher.InvokeAsync(new Action(() =>
                            {
                                
                                try
                                {
                                    IsHomeWebReady = web_Home.CoreWebView2 != null;
                                }
                                catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                { }
                            }));
                            triedHomeWebTimes++;
                        }
                    }
                    catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                    { }
                };
                LastBGs["Home"].RunWorkerCompleted += (s, e) =>
                {
                    //this.Dispatcher.InvokeAsync(new Action(() => {

                    try
                    {
                        if (triedHomeWebTimes <= 5 && web_Home != null && web_Home.CoreWebView2 != null)
                        {
                            if (!string.IsNullOrEmpty(url) && web_Home.Source != new Uri(url))
                                web_Home.CoreWebView2.Navigate(url /*+ "?pwd=" + FullHomeCode*/);

                        }
                        else
                        {
                            //TryOpenHomeWebBrowser(url);
                            //System.Diagnostics.Process.Start("explorer.exe", url);
                        }

                    }
                    catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                    { }
                    LastBGs.Remove("Home");
                    //}));
                };
                LastBGs["Home"].RunWorkerAsync();
            }
            //this.Dispatcher.InvokeAsync(new Action(() => {

            //    try
            //    {
            //        if (web_Home != null && web_Home.CoreWebView2 != null)
            //        {
            //            if (!string.IsNullOrEmpty(url))
            //                web_Home.CoreWebView2.Navigate(url /*+ "?pwd=" + FullDownloadCode*/);

            //        }
            //        else
            //        {
            //            TryOpenHomeWebBrowser(url);
            //        }
            //    }
            //    catch (Exception ex)
            //    { }

            //}));
        }

        private static int triedRegisterWebTimes = 0;
        private static bool IsRegisterWebReady = false;
        private void TryOpenRegisterWebBrowser(string url)
        {
            if (LastBGs.ContainsKey("Register") && LastBGs["Register"] != null) // 如果已经在工作中，就没必要重复发起工作了
                return;

            LastBGs["Register"] = new BackgroundWorker();

            if (triedRegisterWebTimes <= 5)
            {
                if (web_DownloadPage.CoreWebView2 == null)
                {
                    if (web_Register.Source != new Uri(url))
                    {

                        web_Register.Source = new Uri(url);
                        web_Register.EnsureCoreWebView2Async();
                    }

                }
                else
                {
                    web_Register.NavigateToString(url);
                    LastBGs.Remove("Register");
                    return;
                }
            }
           
            if (LastBGs["Register"] != null)
            {
                LastBGs["Register"].DoWork += (s, e) =>
                {

                  
                    try
                    {
                        while (!IsRegisterWebReady)
                        {
                            if (triedRegisterWebTimes > 5)
                                IsRegisterWebReady = true;
                            System.Threading.Thread.Sleep(500);
                            this.Dispatcher.InvokeAsync(new Action(() =>
                            {
                              
                                try
                                {
                                    IsRegisterWebReady = web_Register.CoreWebView2 != null;
                                }
                                catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                { }
                            }));
                            triedRegisterWebTimes++;
                        }
                    }
                    catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                    { }
                };
                LastBGs["Register"].RunWorkerCompleted += (s, e) =>
                {
                    //this.Dispatcher.InvokeAsync(new Action(() => {

                    try
                    {
                        if (triedRegisterWebTimes <= 5 && web_Register != null && web_Register.CoreWebView2 != null)
                        {
                            if (!string.IsNullOrEmpty(url) && web_Register.Source != new Uri(url))
                                web_Register.CoreWebView2.Navigate(url /*+ "?pwd=" + FullRegisterCode*/);

                        }
                        else
                        {
                            //TryOpenRegisterWebBrowser(url);
                            //System.Diagnostics.Process.Start("explorer.exe", url);
                        }

                    }
                    catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                    { }
                    LastBGs.Remove("Register");
                    //}));
                };
                LastBGs["Register"].RunWorkerAsync();
            }
            //this.Dispatcher.InvokeAsync(new Action(() => {

            //    try
            //    {
            //        if (web_Register != null && web_Register.CoreWebView2 != null )
            //        {
            //            if (!string.IsNullOrEmpty(url))
            //                web_Register.CoreWebView2.Navigate(url /*+ "?pwd=" + FullDownloadCode*/);

            //        }
            //        else
            //        {
            //            TryOpenRegisterWebBrowser(url);
            //        }
            //    }
            //    catch (Exception ex)
            //    { }

            //}));
        }

        private List<DataRow> UpdateQueue = new List<DataRow>();

        /// <summary>
        /// 是否需要更新
        /// </summary>
        /// <returns>-1:不需要更新;0:需要更新自身;1:需要更新其他文件</returns>
        private int RequiresUpdate()
        {
            int ShouldUpdate = -1;
            if (ClientCheckList != null && ClientCheckList.Rows.Count > 0)
            {
#region 先检查是否需要更新本登录器
                try
                {
                    DataRow[] found = ClientCheckList.Select("filename = 'GoldenWOWLauncher.exe'");
                    if (found != null && found.Length > 0)
                    {

#region 检查自身是否需要更新
                        DataRow SelfRow = found[0]; // 断言只有一行
                        long size = LocalServices.ToLong(SelfRow["size"]);
                        string hash = LocalServices.ToString(SelfRow["hash"]);
                        string url = LocalServices.ToString(SelfRow["url"]);

                        string FullFileName = Environment.CurrentDirectory +  @"\" + "GoldenWOWLauncher.exe";
                        if (CheckFile(FullFileName, size, hash)) // 如果要更新
                        {
                            UpdateQueue.Clear();
                            UpdateQueue.Add(SelfRow);
                            return 0;
                        }
#endregion

                    }
                }
                catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                {

                }
#endregion

#region 到这里说明登录器不需要更新，那么需要逐个文件进行检查
                try
                {
                    
                    if (UpdateQueue == null)
                        UpdateQueue = new List<DataRow>();
                    UpdateQueue.Clear();
                    pgb_Download.Maximum = ClientCheckList.Rows.Count / 10;
                    pgb_Download.Minimum = 0;
                    pgb_Download.Value = 0;
                    pgb_Download.Visibility = Visibility.Visible;
                    
                    DataTable _table = ClientCheckList.Copy();
                    _table.DefaultView.RowFilter = "filename <> 'GoldenWOWLauncher.exe'";
                    _table = _table.DefaultView.ToTable().Copy();
                    foreach (DataRow row in _table.Rows)
                    {
                        try
                        {
                            long size = LocalServices.ToLong(row["size"]);
                            string hash = LocalServices.ToString(row["hash"]);
                            string url = LocalServices.ToString(row["url"]);
                            string filename = LocalServices.ToString(row["filename"]);
                            string localpath = LocalServices.ToString(row["localpath"]);
#if DEBUGA
                            localpath = @"\Data\zhCN\";
#endif
                            string FullFileName = Environment.CurrentDirectory + localpath + filename;
                            if (CheckFile(FullFileName, size, hash)) // 如果要更新
                            {
                                if (!string.IsNullOrEmpty(url))
                                {
                                    UpdateQueue.Add(row);
                                    if (ShouldUpdate == -1)
                                        ShouldUpdate = 1;
                                }
                                else
                                {
                                        ShouldUpdate = 2;
                                }
                            }
                        }
                        catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                        { }
                        pgb_Download.Value += 0.1;
                    }

                    pgb_Download.Value = 0;
                    pgb_Download.Visibility = Visibility.Hidden;
                }
                catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                {

                }
#endregion
            }
            return ShouldUpdate;
        }

        /// <summary>
        /// 检查文件是否需要更新
        /// </summary>
        /// <param name="fullFileName"></param>
        /// <param name="size"></param>
        /// <param name="hash"></param>
        /// <returns></returns>
        private bool CheckFile(string fullFileName, long size, string hash)
        {
            bool ShouldUpdateSelf = false;

#region 检查文件是否一致
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(fullFileName);
            if (fileInfo != null && fileInfo.Exists)
            {
#region 先检查size是否一致
                if (fileInfo.Length != size)
                {
                    ShouldUpdateSelf = true;
                }
#endregion
#region 再检查Hash是否一致
                else if (LocalServices.GetMD5HashFromFile(fileInfo.FullName) != hash)
                {
                    ShouldUpdateSelf = true;
                }
#endregion
            }
            else
                ShouldUpdateSelf = true;
#endregion

            return ShouldUpdateSelf;
        }

        private void btn_Exit_Click(object sender, RoutedEventArgs e)
        {
            Environment.Exit(-1);
        }

        private void btn_Minmal_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void btn_Maximal_Click(object sender, RoutedEventArgs e)
        {
            
            switch (this.WindowState)
            {
                case WindowState.Maximized:
                    this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    this.btn_Minmal.Visibility = Visibility.Hidden;
                    this.btn_Maximal.Visibility = Visibility.Hidden;
                    this.btn_Exit.Visibility = Visibility.Hidden;
                    this.WindowStyle = WindowStyle.ThreeDBorderWindow;
                    this.WindowState = WindowState.Normal;
                    break;
            }
            
        }
        private void Window_StateChanged(object sender, EventArgs e)
        {
            switch (this.WindowState)
            {
                case WindowState.Maximized:
                    this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    this.btn_Minmal.Visibility = Visibility.Visible;
                    this.btn_Maximal.Visibility = Visibility.Visible;
                    this.btn_Exit.Visibility = Visibility.Visible;
                    this.WindowStyle = WindowStyle.None;
                    this.WindowState = WindowState.Maximized;
                    break;
            }

        }

        System.Net.WebClient? DOWNLOADER = null;
        private void DOWNLOADER_DownloadFileCompleted(object? sender, AsyncCompletedEventArgs e)
        {
            this.Dispatcher.Invoke(new Action(() => {
                pgb_Download.Value = pgb_Download.Maximum;
            }));

            this.Dispatcher.Invoke(new Action(() => {
                try
                {
                    if (Environment.ProcessPath != null)
                    {
                        DataRow DownloadingRow = UpdateQueue[0];
                        string url = LocalServices.ToString(DownloadingRow["url"]);
                        string filename = LocalServices.ToString(DownloadingRow["filename"]);
                        string localpath = LocalServices.ToString(DownloadingRow["localpath"]);

                        FullPathEnsure(localpath);

#region 从临时文件夹中移动到目标文件夹

#region 目标位置先删
                        if (System.IO.File.Exists(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", localpath + @"\" + filename)))
                        {
                            try
                            {
                                System.IO.File.Delete(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", localpath + @"\" + filename));
                            }
                            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                            { }
                        }
#endregion

#region 后移
                        try
                        {
                            System.IO.File.Move(
                                Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" +  @"\" + filename)
                                ,
                                Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", localpath + @"\" + filename)
                                );
                        }
                        catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                        { }
#endregion

#endregion

                   
                        //pgb_Download.Visibility = Visibility.Hidden;
                        if (UpdateQueue != null)
                        {
                            UpdateQueue.Remove(DownloadingRow); // 更新队列中移除已完成的记录
                            if (DOWNLOADER != null && UpdateQueue.Count > 0) // 如果还有记录，就继续下载
                            {
                                try {
                                    int CurrentProgress = 1;
                                    int TotalProgress = 0;
                                    string[] progresses = LocalServices.ToString(lab_Progress.Content).Split("/");
                                    if (progresses != null && progresses.Length > 0)
                                    {
                                        CurrentProgress = LocalServices.ToInt(progresses[0]);
                                        TotalProgress = LocalServices.ToInt(progresses[1]);
                                        CurrentProgress++;
                                        lab_Progress.Content = CurrentProgress + @"/" + TotalProgress;
                                    }

                                }
                                catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                { }
                                DownloadingRow = UpdateQueue[0];
                                url = LocalServices.ToString(DownloadingRow["url"]);
                                filename = LocalServices.ToString(DownloadingRow["filename"]);
                                localpath = LocalServices.ToString(DownloadingRow["localpath"]);
                                pgb_Download.Value = 0;

                                DOWNLOADER.DownloadFileAsync(new Uri(url), Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" +  filename));
                                pgb_Download.Visibility = Visibility.Visible;
                            }
                            else if (UpdateQueue.Count == 0) // 如果记录已经空了，说明更新完成
                            {
                                MessageBox.Show("更新完成!");
                                pgb_Download.Value = 0;
                                pgb_Download.Visibility = Visibility.Hidden;
                                lab_Progress.Visibility = Visibility.Hidden;

#region 切换按钮成进入状态
                                btn_Enter.IsEnabled = true;
                                txt_Enter.Text = "进入";
                                status = Status.Playable;
                                btn_Enter.IsHitTestVisible = true;
#endregion
                            }
                        }
                


                    }

                }
                catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                { }
            }));
        }

        /// <summary>
        /// 确保路径存在
        /// </summary>
        /// <param name="Path">程序运行路径的相对路径</param>
        private void FullPathEnsure(string Path)
        {
            try
            {
                if (Environment.ProcessPath != null)
                {
                    string[] pathSections = Path.Split('\\');
                    string lastPath = string.Empty;
                    foreach (string path in pathSections)
                    {
                        if (string.IsNullOrEmpty(path))
                            continue;
                        if (!System.IO.Directory.Exists(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", lastPath + @"\" + path)))
                        {
                            try
                            {
                                System.IO.Directory.CreateDirectory(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", lastPath + @"\" + path));
                            }
                            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                            { }
                        }
                        if (!string.IsNullOrEmpty(lastPath))
                            lastPath += @"\";
                        lastPath += path;
                    }
                }
              
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }
        }
        private void DOWNLOADER_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
        {
            this.Dispatcher.Invoke(new Action(()=> {
                double bytesIn = double.Parse(e.BytesReceived.ToString());
                double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
                double percentage = bytesIn / totalBytes * 1000;
                pgb_Download.Value = percentage;
            }));
        }
        
        private void ClearAllNavigationBtnBackground()
        {
            
            try
            {
                btn_Home.IsHitTestVisible = true;
                btn_Home.Background = null;
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }

            try
            {
                btn_Register.IsHitTestVisible = true;
                btn_Register.Background = null;
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }

            try
            {
                btn_FullDownload.IsHitTestVisible = true;
                btn_FullDownload.Background = null;
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }

            try
            {
                btn_Addons.IsHitTestVisible = true;
                btn_Addons.Background = null;
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }
            
            try
            {
                btn_News.IsHitTestVisible = true;
                btn_News.Background = null;
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }

        }

        private string HomeURL = "https://golden-wow.com/";
        private void btn_Home_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (web_Home.CoreWebView2 == null)
                {
                    if (sender == null)
                    {
                        btn_News_Click(sender, e);
                        return;
                    }
                    try
                    {
                        if (triedHomeWebTimes > 5 && !string.IsNullOrEmpty(HomeURL))
                            System.Diagnostics.Process.Start("explorer.exe", HomeURL);
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.Log(ex.Message + ":" + ex.StackTrace);
                        MessageBox.Show("浏览器打开失败");
                    }
                    return;
                }

                LastClicked = "home";
                ClearAllNavigationBtnBackground();
                web_Home.Visibility = Visibility.Visible;
                web_Register.Visibility = Visibility.Hidden;
                web_DownloadPage.Visibility = Visibility.Hidden;
                //if (sender.ToString() != "GoldenWOWLauncher.MainWindow")
                //{

                //    this.TryOpenHomeWebBrowser(HomeURL);
                //}
    
                msg_News.Visibility = Visibility.Hidden;
                this.lv_Options.Visibility = Visibility.Hidden;
                btn_Home.IsHitTestVisible = false;
                btn_Home.Background = Hover;
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }
        }


        private string RegisterURL = "http://103.91.211.64/";

        private string LastClicked = string.Empty;

        private void btn_Register_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (web_Register.CoreWebView2 == null)
                {
                    if (sender == null)
                    {
                        btn_News_Click(sender, e);
                        return;
                    }
                    try
                    {
                        if (triedRegisterWebTimes > 5 && !string.IsNullOrEmpty(RegisterURL))
                        {
                            System.Diagnostics.Process.Start("explorer.exe", RegisterURL);
                           
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.Log(ex.Message + ":" + ex.StackTrace);
                        MessageBox.Show("浏览器打开失败");
                    }
                    return;
                }
                LastClicked = "register";
                ClearAllNavigationBtnBackground();
                //this.TryOpenRegisterWebBrowser(RegisterURL);
                web_Home.Visibility = Visibility.Hidden;
                web_DownloadPage.Visibility = Visibility.Hidden;
                msg_News.Visibility = Visibility.Hidden;
                this.lv_Options.Visibility = Visibility.Hidden;
                web_Register.Visibility = Visibility.Visible;
                btn_Register.IsHitTestVisible = false;
                btn_Register.Background = Hover;
            
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }
        }

        private void btn_FullDownload_Click(object sender, RoutedEventArgs e)
        {
            try
            {
#if !DEBUG
                
#endif
                if (web_DownloadPage.CoreWebView2 == null)
                {
                    if (sender == null)
                    {
                        btn_News_Click(sender, e);
                        return;
                    }
                    try
                    {
                        if (triedDownloadWebTimes > 5 && !string.IsNullOrEmpty(FullDownloadUrl))
                            System.Diagnostics.Process.Start("explorer.exe", FullDownloadUrl);
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.Log(ex.Message + ":" + ex.StackTrace);
                        MessageBox.Show("浏览器打开失败");
                    }
                    return;
                }
                LastClicked = "fulldownload";
                ClearAllNavigationBtnBackground();
                //this.TryOpenDownloadWebBrowser(FullDownloadUrl);
                web_Register.Visibility = Visibility.Hidden;
                web_Home.Visibility = Visibility.Hidden;
                msg_News.Visibility = Visibility.Hidden;
                this.lv_Options.Visibility = Visibility.Hidden;
                web_DownloadPage.Visibility = Visibility.Visible;
                btn_FullDownload.IsHitTestVisible = false;
                btn_FullDownload.Background = Hover;

                if (!string.IsNullOrEmpty(FullDownloadCode))
                {
                    ClipboardHelper.CopyText(FullDownloadCode);
                    MessageBox.Show("分享码是：" + FullDownloadCode+ "\r\n\r\n已复制进剪贴板。");
                }
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }
        }

        private void btn_Addons_Click(object sender, RoutedEventArgs e)
        {
            LastClicked = "addons";
            ClearAllNavigationBtnBackground();
            
            msg_News.Visibility = Visibility.Hidden;
            web_Home.Visibility = Visibility.Hidden;
            web_Register.Visibility = Visibility.Hidden;
            web_DownloadPage.Visibility = Visibility.Hidden;
            this.lv_Options.Visibility = Visibility.Visible;
            btn_Addons.IsHitTestVisible = false;
            btn_Addons.Background = Hover;
        }

        private void btn_Enter_Click(object sender, RoutedEventArgs e)
        {
#region 进行处理
            switch (status)
            {
                case Status.Playable:
                    {
#region 清理缓存
                        try
                        {
                            if (System.IO.Directory.Exists("Cache"))
                            {
                                System.IO.Directory.Delete("Cache", true);
                            }
                        }
                        catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                        { }
#endregion

#region 设置Realmlist
                        try
                        {
                            string[] locales = { "frFR", "deDE", "enGB", "enUS", "itIT", "koKR", "zhCN", "zhTW", "ruRU", "esES", "esMX", "ptBR", "enCN" };
                            foreach (string locale in locales)
                            {
                                if (System.IO.Directory.Exists("Data" + @"\" + locale))
                                {
                                    System.IO.File.WriteAllText("Data" + @"\" + locale + @"\" + "realmlist.wtf", "set realmlist \""+ RealmList + "\"");
                                }
                            }
                        }
                        catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                        { }
#endregion

#region 运行
                        try
                        {
                            if (System.Environment.CurrentDirectory != null && System.IO.File.Exists(System.Environment.CurrentDirectory + @"\" + "Game.exe"))
                            {
                                System.Diagnostics.Process.Start("Game.exe");
                                //Environment.Exit(-1);
                            }

                        }
                        catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); MessageBox.Show("运行失败"); }
                        {
                            
                        }
#endregion
                    }
                    break;
                case Status.ShouldDownload:
                    {
                        //不做任何事，装作不能按
                    }
                    break;
                case Status.ShouldUpdate:
                    try
                    {
#region 更新按钮状态
                        btn_Enter.IsEnabled = true;
                        txt_Enter.Text = "更新中";
                        status = Status.ShouldDownload;
                        btn_Enter.IsHitTestVisible = false;
#endregion
                    }
                    catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                    { }
                    try
                    {
#region 更新
                        if (UpdateQueue != null && UpdateQueue.Count > 0 && Environment.ProcessPath != null)
                        {
                            lab_Progress.Content = "1/" + (UpdateQueue.Count).ToString();
                            pgb_Download.Visibility = Visibility.Hidden;
                            pgb_Download.Maximum = 1000;
                            pgb_Download.Minimum = 0;
                            pgb_Download.Value = 0;
                            pgb_Download.Visibility = Visibility.Visible;
                            lab_Progress.Visibility = Visibility.Visible;
                            DataRow row = UpdateQueue[0];
                            //long size = Services.ToLong(row["size"]);
                            //string hash = Services.ToString(row["hash"]);
                            string url = LocalServices.ToString(row["url"]);
                            string filename = LocalServices.ToString(row["filename"]);
                            string localpath = LocalServices.ToString(row["localpath"]);
                            if (DOWNLOADER != null)
                            {
                                try
                                {
                                    DOWNLOADER.Dispose();
                                    DOWNLOADER = null;
                                }
                                catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                { }
                            }
                            DOWNLOADER = new System.Net.WebClient();

                            DOWNLOADER.DownloadProgressChanged += DOWNLOADER_DownloadProgressChanged;
                            DOWNLOADER.DownloadFileCompleted += DOWNLOADER_DownloadFileCompleted;

                            FullPathEnsure("Downloaded");
#region 先下载到临时文件夹

#region 先删
                            if (System.IO.File.Exists(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename)))
                            {
                                try
                                {
                                    System.IO.File.Delete(Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename));
                                }
                                catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                                { }
                            }
#endregion

#region 后下
                            {

                                DOWNLOADER.DownloadFileAsync(new Uri(url), Environment.ProcessPath.ToLower().Replace("goldenwowlauncher.exe", "Downloaded" + @"\" + filename));
                              
                            }
#endregion

#endregion
                        }

#endregion
                    }
                    catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                    { }
                    break;
            }

#endregion
        }

        private string NewsURL = "https://golden-wow.com/contact/";
        private void btn_News_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                LastClicked = "news";
                ClearAllNavigationBtnBackground();
                //web_MainDownload.Visibility = Visibility.Visible;
                //this.TryOpenWebBrowser(NewsURL);
                web_Home.Visibility = Visibility.Hidden;
                web_Register.Visibility = Visibility.Hidden;
                web_DownloadPage.Visibility = Visibility.Hidden;
                this.lv_Options.Visibility = Visibility.Hidden;
                msg_News.Visibility = Visibility.Visible;
                btn_News.IsHitTestVisible = false;
                btn_News.Background = Hover;
            }
            catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
            { }
        }

        private bool IsHiding = false;

        private void btn_ShowHideAll_Click(object sender, RoutedEventArgs e)
        {
            switch (IsHiding)
            {
                case true:
#region 显示全部
                    {
                        IsHiding = false;
                        btn_ShowHideAll.ToolTip = "隐藏所有部件";
                        try
                        {
                            //web_DownloadPage.Visibility = Visibility.Collapsed;
                            //web_Home.Visibility = Visibility.Collapsed;
                            //web_Register.Visibility = Visibility.Collapsed;
                            //msg_News.Visibility = Visibility.Collapsed;
                            grd_Blur.Visibility = Visibility.Visible;
                            btn_Addons.Visibility = Visibility.Visible;
                            btn_FullDownload.Visibility = Visibility.Visible;
                            btn_News.Visibility = Visibility.Visible;
                            btn_Register.Visibility = Visibility.Visible;
                            btn_Home.Visibility = Visibility.Visible;

                            btn_ShowHideAll.OpacityMask = HideAll;
                            switch (LastClicked)
                            {
                                case "home":
                                    btn_Home_Click(null, e);
                                    break;
                                case "register":
                                    btn_Register_Click(null, e);
                                    break;
                                case "addons":
                                    btn_Addons_Click(null, e);
                                    break;
                                case "news":
                                    btn_News_Click(null, e);
                                    break;
                                case "fulldownload":
                                    btn_FullDownload_Click(null, e);
                                    break;
                            }
                        }
                        catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                        {

                        }

                    }
#endregion
                    break;
                default:
#region 隐藏全部
                    {
                        IsHiding = true;
                        btn_ShowHideAll.ToolTip = "显示所有部件";
                        try
                        {
                            web_DownloadPage.Visibility = Visibility.Collapsed;
                            web_Home.Visibility = Visibility.Collapsed;
                            web_Register.Visibility = Visibility.Collapsed;
                            msg_News.Visibility = Visibility.Collapsed;
                            grd_Blur.Visibility = Visibility.Collapsed;
                            btn_Addons.Visibility = Visibility.Collapsed;
                            btn_FullDownload.Visibility = Visibility.Collapsed;
                            btn_News.Visibility = Visibility.Collapsed;
                            btn_Register.Visibility = Visibility.Collapsed;
                            btn_Home.Visibility = Visibility.Collapsed;

                            btn_ShowHideAll.OpacityMask = ShowAll;
                        }
                        catch (Exception ex) { Logger.Instance.Log(ex.Message + ":" + ex.StackTrace); }
                        { 
                        
                        }
                     
                    }
#endregion
                    break;
            }
        }

     
    }

     
}
